package cn.jilian.meta.handler.support;

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializerProvider;

import cn.jilian.meta.handler.domain.FuncCallExpression;

public class FuncCallExpressionSerializer extends JsonSerializer<FuncCallExpression> {

	private ObjectMapper objectMapper;
	
	private ObjectWriter writer;
	
	public FuncCallExpressionSerializer() {
		this.objectMapper=new ObjectMapper();
		objectMapper.setSerializationInclusion(Include.NON_NULL); 
		this.writer=objectMapper.writerWithDefaultPrettyPrinter();
	}
	
	@Override
	public void serialize(FuncCallExpression value, JsonGenerator gen, SerializerProvider serializers)
			throws IOException, JsonProcessingException {
		String expr=value.getExpr();
		
		Object[] args=value.getArgs();
		StringBuilder sb=new StringBuilder(expr).append("(");
		if(args!=null&&args.length>0) {
			for(Object arg:args) {
				if(String.class.isAssignableFrom(arg.getClass())) {
					sb.append("'")
					.append(arg).append("'");
				}else if(Number.class.isAssignableFrom(arg.getClass())) {
					sb.append(arg);
				}else {
					
					sb.append(writer.writeValueAsString(arg));
				}
				sb.append(",");
				
			}
			sb.setLength(sb.length()-1);
		}
		sb.append(");");
		gen.writeRawValue(sb.toString());
	}

}
